package com.cdtu.outtake.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdtu.outtake.dao.AddressMapper;
import com.cdtu.outtake.domain.Address;
import com.cdtu.outtake.service.IAddressService;
import com.cdtu.outtake.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author : shl
 * @Date 2024/1/13 23:33
 */
@Service
@RequiredArgsConstructor
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
        implements IAddressService {
    private final IUserService userService;

    @Override
    public List<Address> getAddressesByUserId(Long userId) {
        return this.baseMapper.selectList(new QueryWrapper<Address>().eq("user_id", userId));
    }

    @Override
    public void create(Address address) {
        Long userId = userService.getMyUserId();
        List<Address> addressList = baseMapper.selectList(new QueryWrapper<Address>()
                .eq("user_id", userId));
        if (null == addressList || addressList.size() == 0) {
            address.setDef(true);
            address.setUserId(userId);
            this.save(address);
            return;
        }
        if (Boolean.TRUE.equals(address.getDef())) {
            Address defaultAddress = this.getDefaultAddressesByUserId(userId);
            defaultAddress.setDef(false);
            baseMapper.updateById(defaultAddress);
        }
        address.setUserId(userId);
        this.save(address);
    }

    @Override
    public void delete(Long id) {
        baseMapper.delete(new QueryWrapper<Address>()
                .eq("id", id)
                .eq("user_id", userService.getMyUserId()));
    }

    @Override
    @Transactional
    public void update(Address address) {
        if (Boolean.TRUE.equals(address.getDef())) {
            Long userId = userService.getMyUserId();
            Address defaultAddress = this.getDefaultAddressesByUserId(userId);
            if(defaultAddress!=null){
                defaultAddress.setDef(false);
                baseMapper.updateById(defaultAddress);
            }
        }
        baseMapper.updateById(address);
    }

    @Override
    public Address getDefaultAddressesByUserId(Long userId) {
        return this.baseMapper.selectOne(new QueryWrapper<Address>()
                .eq("def", true)
                .eq("user_id", userId));
    }

    @Override
    public Address getAddressById(Long id) {
        return baseMapper.selectById(id);
    }
}
